package com.mashibing.jvm.c3_jmm.cacheling;

/**
 * 第一种写法，同一个缓存行可能位于不同的cpu
 * 输出： 32, 32, 28, 29, 23, 29, 28, 28, 29, 22, 26, 27, 28, 26, 22, 28, 26, 27, 22, 28,
 */
public class T01_CacheLinePadding {
    private static class T{
        public volatile long x = 0;
    }
    public static T[] arr = new T[2];
    static {
        arr[0] = new T();
        arr[1] = new T();
    }

    public static void testMethod() throws InterruptedException {
        final long len = 1000_0000L;
        Thread t1 = new Thread(()->{
            for (long i = 0; i < len; i++) {
                arr[0].x = i;
            }
        });

        Thread t2 = new Thread(()->{
            for (long i = len; i > 0; i--) {
                arr[1].x = i;
            }
        });

        final long start = System.nanoTime();
        t1.start();t2.start();
        t1.join();t2.join();
        System.out.print((System.nanoTime()-start)/len + ", ");

    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 20; i > 0; i--) {
            testMethod();
        }
    }
}
